<template>
  <div class="end">
    <div class="ret">
      <van-nav-bar title="目的地、途经点录入" left-text="返回" left-arrow @click-left="toStartPoint()"/>
    </div>
    <div>
      <van-field
          v-model="fieldValue1"
          is-link
          readonly
          label="地区"
          placeholder="请选择所在地区"
          @click="show1 = true"
      />
      <van-popup v-model="show1" round position="bottom">
        <van-cascader
            v-model="cascaderValue1"
            title="请选择途经点地区"
            :options="options"
            @close="show1 = false"
            @finish="onFinish"
        />
      </van-popup>
    </div>
    <!--  途经点搜索-->
    <!--    <div>-->
    <!--      <div id="mapContainer"></div>-->
    <!--      <div id="myPageTop">-->
    <!--        <table>-->
    <!--          <tr>-->
    <!--            <td>-->
    <!--              <label>请输入途经点：</label>-->
    <!--            </td>-->
    <!--          </tr>-->
    <!--          <tr>-->
    <!--            <td>-->
    <!--              <input id="tipinput1" v-model="keyword2" class="input"/>-->
    <!--            </td>-->
    <!--          </tr>-->
    <!--        </table>-->
    <!--      </div>-->
    <!--    </div>-->

    <div>
      <van-field
          v-model="fieldValue2"
          is-link
          readonly
          label="地区"
          placeholder="请选择终点地区"
          @click="show2 = true"
      />
      <van-popup v-model="show2" round position="bottom">
        <van-cascader
            v-model="cascaderValue2"
            title="请选择所在地区"
            :options="options"
            @close="show2 = false"
            @finish="onFinish2"
        />
      </van-popup>
    </div>
    <!--  终点搜索-->
    <div>
      <div id="mapContainer"></div>
      <div id="myPageTop">
        <table>
          <tr>
            <td>
              <label>请输入终点：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input id="tipinput" v-model="keyword" class="input"/>
            </td>
          </tr>
          <tr>
            <td>
              <label>经纬度：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input v-model="keyword1" class="input"/>
              <input type="hidden" id="endLatitudeAndLongitude" disabled v-model="endLatitudeAndLongitude"/>
              <input id="geo" type="button" class="btn" value="地址 -> 经纬度" @click="hanld">
            </td>
          </tr>
        </table>
      </div>
    </div>

    <div class="dong" @click="toHomeAndCompany">
      <div class="image">
        <van-icon name="wap-home-o"/>
      </div>
      <div class="hom"><span>家</span></div>
      <div class="didian">大江苑</div>
    </div>
    <div class="si" @click="toHomeAndCompany">
      <div class="image">
        <van-icon name="cashier-o"/>
      </div>
      <div class="firm"><span>公司</span></div>
      <div class="sdi">设置公司地址</div>
    </div>
    <div class="tu" @click="toMap">
      <div class="image">
        <van-icon name="location-o"/>
      </div>
      <div class="firm"><span>地图选址</span></div>
    </div>

    <div>
      <div class="transit">
        <van-button icon="plus" type="primary" class="left">途经点</van-button>
        <span class="span">可再添加1个</span>
        <van-button type="primary" class="right" round>完成</van-button>
      </div>
    </div>

    <div class="lishi">
      <van-list>
        <div class="history">
          <van-cell v-for="item in historyList" :key="item.id">
            <div>
              <div class="">{{ item.addressName }}</div>
              <div class="">{{ item.provinceMessage }}</div>
            </div>
          </van-cell>
        </div>
      </van-list>
    </div>
    <van-button type="primary" style="width: 90%;margin-left: 5px;margin-top: 20px;background-color: #4B9EFF" @click="toRoute">确认</van-button>

  </div>
</template>

<script>
import axios from "axios";
import {useCascaderAreaData} from '@vant/area-data';
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  data() {
    return {
      currentTime: '',
      networkStatus: '',
      batteryLevel: '',
      isCharging: false,
      selectedValue: '',
      cityList: [],
      districtList: [],
      search: "",
      historyList: [],
      historys: {
        addressName: null,
        provinceMessage: null,
      },
      show1: false,
      show2: false,
      fieldValue1: '',
      cascaderValue1: '',
      fieldValue2: '',
      cascaderValue2: '',
      options: useCascaderAreaData(),


      // 途经点终点搜索框输入内容
      map: '',
      keyword: '',
      keyword1: '',
      auto: null,
      placeSearch: null,

      geocoder: null,
      marker: null,
      location: {},
      flag: false,
      position:null,

      //出发地经纬度
      startLatitudeAndLongitude: "",
      // 目的地经纬度
      endLatitudeAndLongitude: "",

      //出发地
      startaddress: "",
      //目的地
      endaddress: "",

      order:{
        //出发地
        startaddress: "",
        //目的地
        endaddress: "",
      },
      flag2: true,
    };
  },
  created() {
    this.findByHistory();
    this.startLocation();
    this.findFlag()
    this.homeAndCompany()
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    homeAndCompany(){
      this.keyword1 = this.$route.query.startLnglat
      this.keyword = this.$route.query.keyword
    },
    toMap() {
      this.$router.push({
        path: '/mapSite',
      })
    },
    toHomeAndCompany(){
      this.$router.push({
        path: '/homeAndCompany',
      })
    },
    findFlag(){
      this.startaddress=this.$route.query.startaddress
      this.startLatitudeAndLongitude=this.$route.query.startLatitudeAndLongitude
      this.flag2=this.$route.query.flag2
      if (this.flag2!=undefined){
        this.flag=this.flag2;
      }
      console.log("flag2:" +this.flag2)
      console.log("startaddress:" + this.startaddress)
    },
    toRoute(){
      console.log("出发地经纬度:" + this.startLatitudeAndLongitude)
      console.log("目的地经纬度:" + this.endLatitudeAndLongitude)
      console.log(this.flag2)
      if (this.flag2){
        console.log(1)
        this.$router.push({
          path: '/helpCartOne',
          query: {
            startaddress: this.startaddress,
            endaddress: this.endaddress,
            startLatitudeAndLongitude: this.startLatitudeAndLongitude,
            endLatitudeAndLongitude: this.endLatitudeAndLongitude
          }
        })
      }else{
        console.log(2)
        this.$router.push({
          path: '/routeCart',
          query: {
            startLatitudeAndLongitude: this.startLatitudeAndLongitude,
            endLatitudeAndLongitude: this.endLatitudeAndLongitude.toString()
          }
        })
      }

    },
    toStartPoint(){
      this.$router.push({
        path: '/startPoint',
        query: {
          startaddress: this.startaddress,
        }
      })
    },
    hanld() {
      this.flag = true;
      this.initMap()
    },
    startLocation() {
      this.startLatitudeAndLongitude = this.$route.query.startLatitudeAndLongitude;
      console.log("获取出发地经纬度：", this.startLatitudeAndLongitude);
    },
    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "9708bfa416d306b9dbaf55ea4e4a25f2",
      };
      const vm = this;
      AMapLoader.load({
        key: "e6effe38515227141202b9fb6749424e", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar", //工具条
          "AMap.Scale", // 比例尺
          "AMap.Geolocation", //定位
          "AMap.PlaceSearch", //查询
          'AMap.AutoComplete',
          "AMap.Marker"
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            const map = new AMap.Map("mapContainer", {
              // 设置地图容器id
              viewMode: "3D", // 是否为3D地图模式
              zoom: 11, // 初始化地图级别
              resizeEnable: true,
              center: [116.397428, 39.90923], // 初始化地图中心点位置
            });

            //构造地点查询类
            AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete', "AMap.Geolocation", "AMap.Marker", "AMap.Geocoder"],
                function () {
                  var geocoder = new AMap.Geocoder({
                    city: "010", //城市设为北京，默认：“全国”
                  });
                  //输入提示
                  var autoOptions = {
                    input: "tipinput"
                  };
                  vm.auto = new AMap.AutoComplete(autoOptions);
                  vm.placeSearch = new AMap.PlaceSearch({
                    map: map
                  });
                  // 定位
                  if (vm.flag === false) {
                    var geolocation = new AMap.Geolocation({
                      enableHighAccuracy: true,//是否使用高精度定位，默认:true
                      timeout: 500000,          //超过10秒后停止定位，默认：5s
                      buttonPosition: 'RB',    //定位按钮的停靠位置
                      buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                      zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
                      needAddress: true,      //是否返回地址信息
                      city: '010'
                    });
                    map.addControl(geolocation);
                    geolocation.getCurrentPosition(function (status, result) {
                      if (status === 'complete') {
                        onComplete(result);
                      } else {
                        onError(result)
                      }
                    });
                  }

                  const marker = new AMap.Marker();
                  const keyword = vm.keyword;//输入的内容
                  geocoder.getLocation(keyword, function (status, result) {
                    if (status === 'complete' && result.geocodes.length) {
                      // onComplete(result)
                      const endLatitudeAndLongitude = result.geocodes[0].location;
                      console.log(endLatitudeAndLongitude)
                      // 获取经纬度
                      vm.keyword1 = endLatitudeAndLongitude;
                      console.log("目的地经纬度:" + endLatitudeAndLongitude)
                      vm.endLatitudeAndLongitude = endLatitudeAndLongitude;
                      document.getElementById('endLatitudeAndLongitude').value = endLatitudeAndLongitude;
                      marker.setPosition(endLatitudeAndLongitude);
                      map.add(marker);
                      map.setFitView(marker);

                      console.log("输入地区的经纬度:", vm.keyword1.lng + "," + vm.keyword1.lat);
                      vm.endLatitudeAndLongitude = vm.keyword1.lng + "," + vm.keyword1.lat;
                      // 逆地理编码获取目的地地址信息
                      var end = vm.endLatitudeAndLongitude.split(",").map(item => parseFloat(item));
                      // 寻找结束地址的方法
                      geocoder.getAddress(end, function (status, result) {
                        if (status === 'complete' && result.regeocode) {
                          vm.endaddress = result.regeocode.formattedAddress;
                          console.log("目的地地址：", vm.endaddress)
                        } else {
                          console.log("获取结束地址失败");
                        }
                      });
                      console.log("end:", end)

                    } else {
                      console.log("根据地址查询位置失败")
                    }
                  });


                  //提示查询定位
                  const auto = new AMap.AutoComplete(autoOptions);
                  const placeSearch = new AMap.PlaceSearch({
                    map: map
                  });  //构造地点查询类
                  auto.on("select", select);//注册监听，当选中某条记录时会触发

                  function select(e) {
                    placeSearch.setCity(e.poi.adcode);
                    placeSearch.search(e.poi.name);  //出发地查询
                  }
                });

            function onComplete(data) {
              console.log("定位成功!");
              // findalltext.position=data.position;
              self.position = data.position + "";
              console.log(self.position);
              console.log("定位结果:" + data.position);
              console.log("定位类别:" + data.location_type);
              console.log("精度:" + data.accuracy + "米");
              console.log("是否经过偏移:" + data.isConverted);
              // document.getElementById('status').innerHTML='定位成功'
              var str = [];
              str.push('定位结果：' + data.position);
              str.push('定位类别：' + data.location_type);
              if (data.accuracy) {
                str.push('精度：' + data.accuracy + ' 米');
              }//如为IP精确定位结果则没有精度信息
              str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
              // this.position=str;
              // document.getElementById('result').innerHTML = str.join('<br>');
            }

            //解析定位错误信息
            function onError(data) {
              console.log("定位失败!")
              console.log("失败原因排查信息:" + data.message)
              // 定位失败
              // document.getElementById('status').innerHTML='定位失败'
              // document.getElementById('result').innerHTML = '失败原因排查信息:'+data.;message
            }

          });
    },

    toHomeIndex() {
      this.$router.push({
        path: '/',
        query:{
          startaddress:this.startaddress,
          endaddress:this.endaddress
        }
      })
    },
    onFinish2({selectedOptions}) {
      this.show2 = false;
      this.fieldValue2 = selectedOptions.map((option) => option.text).join('/');
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({selectedOptions}) {
      this.show1 = false;
      this.fieldValue1 = selectedOptions.map((option) => option.text).join('/');
    },
    findByHistory() {
      axios.post('http://localhost:8081/passenger/history/findHistoryList', this.historys).then(response => {
        console.log(response);
        this.historyList = response.data.data;
      })
    },
  }
};
</script>

<style>

.end {
  width: 100%;
  height: 100%;

  #mapContainer {
    width: 100%;
    height: 50vh;
  }

  #myPageTop {
    margin-top: 8px;
    margin-left: 10px;
  }

  .input {
    width: 100%;
    height: 25px;
  }

  .search {
    width: 100%;
    height: 50px;
    float: left;
  }

  .transit {
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .left {
    float: left;
    margin-left: 22px;
  }

  .span {
    margin-left: -398px;
    font-size: 11px;
  }

  .right {
    float: left;
    margin-left: 261px;
    margin-top: -40px;
    background-color: #4B9EFF;
    width: 80px;
  }

  .lishi {
    width: 100%;
    height: 100px;
    margin-top: 80px;
    line-height: 50px;
    text-align: center;
    //background-color: #4EA9CB;
  }

  .dong {
    width: 28%;
    height: 61px;
    margin-top: 44px;
    line-height: 20px;
    text-align: center;
    background-color: #4B9EFF;
    margin-left: 20px;
  }

  .tu {
    float: left;
    width: 28%;
    height: 65px;
    margin-top: -64px;
    line-height: 20px;
    text-align: center;
    background-color: #f6e992;
    margin-left: 254px;
  }

  .si {
    float: left;
    width: 28%;
    height: 65px;
    margin-top: -61px;
    line-height: 20px;
    text-align: center;
    background-color: #f6e992;
    margin-left: 135px;
  }

  .image {
    width: 15px;
    height: 15px;
    margin-left: 10px;
    margin-top: 10px;
  }

  .firm {
    width: 30px;
    height: 30px;
    line-height: 20px;
    text-align: center;
    margin-left: 39px;
    font-size: 15px;
    margin-top: -16px;
  }

  .hom {
    width: 30px;
    height: 30px;
    line-height: 15px;
    text-align: center;
    margin-left: 39px;
    font-size: 15px;
  }

  .sdi {
    width: 103px;
    height: 30px;
    line-height: 20px;
    text-align: center;
    margin-left: 9px;
    font-size: 11px;
  }

  .didian {
    width: 50px;
    height: 30px;
    line-height: 7px;
    text-align: center;
    margin-left: 30px;
    font-size: 15px;
  }

  .search {
    width: 100%;
    height: 70px;
  }
}
</style>